<template>
  <div class="user-info-container">
    <div class="action-bar">
      <el-button class="action-btn" @click="goBack">返回</el-button>
    </div>
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="3" animated />
    </div>

    <div v-else class="user-info-card">
      <h2>个人信息</h2>
      <el-form :model="userInfo" label-width="120px">
        <el-form-item label="用户ID">
          <el-input v-model="userInfo.userId" disabled></el-input>
        </el-form-item>
        <el-form-item label="用户名">
          <el-input v-model="userInfo.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="userInfo.email" disabled></el-input>
        </el-form-item>
        <el-form-item label="会员状态">
          <el-input :value="userInfo.isVip === '是' ? 'VIP会员' : '普通用户'" disabled></el-input>
        </el-form-item>
        <el-form-item label="用户状态">
          <el-input :value="userInfo.status === 1 ? '未登录' : '已登录'" disabled></el-input>
        </el-form-item>
      </el-form>
      <div class="action-buttons">
        <el-button type="primary" @click="showChangePasswordDialog">修改密码</el-button>
        <el-button type="danger" @click="logout">退出登录</el-button>
      </div>
    </div>

    <!-- 修改密码对话框 -->
    <el-dialog title="修改密码" v-model="changePasswordDialogVisible">
      <el-form :model="passwordForm" :rules="passwordRules" ref="passwordFormRef">
        <el-form-item label="当前密码" prop="currentPassword">
          <el-input v-model="passwordForm.currentPassword" type="password" show-password></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="passwordForm.newPassword" type="password" show-password></el-input>
        </el-form-item>
        <el-form-item label="确认新密码" prop="confirmPassword">
          <el-input v-model="passwordForm.confirmPassword" type="password" show-password></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="changePasswordDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="changePassword">确认修改</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import axios from 'axios'

const router = useRouter()

// 用户信息（从后端获取）
const userInfo = reactive({
  userId: '',
  username: '',
  email: '',
  isVip: '',
  status: ''
})

// 加载状态
const loading = ref(true)

// 修改密码对话框相关
const changePasswordDialogVisible = ref(false)
const passwordFormRef = ref(null)
const passwordForm = reactive({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 密码验证规则
const passwordRules = reactive({
  currentPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value === passwordForm.currentPassword) {
          callback(new Error('新密码不能与当前密码相同'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
})

// 获取用户信息
const fetchUserProfile = async () => {
  try {
    loading.value = true
    const username = localStorage.getItem('userName')
    console.log(username)

    if (!username) {
      ElMessage.error('未找到用户信息，请重新登录')
      router.push('/login')
      return
    }

    // 对用户名进行 URL 编码
    const encodedUsername = encodeURIComponent(username);

    const response = await axios.get('http://localhost:8888/api/profile', {
      headers: {
        'X-Username': encodedUsername
      }
    })

    Object.assign(userInfo, response.data)
    loading.value = false
    ElMessage.success('获取用户信息成功')
    console.log(userInfo)

  } catch (error) {
    console.error('获取用户信息失败:', error)
    ElMessage.error('获取用户信息失败: ' + (error.response?.data?.message || error.message))
    loading.value = false
  }
}

// 显示修改密码对话框
const showChangePasswordDialog = () => {
  // 重置表单
  passwordForm.currentPassword = ''
  passwordForm.newPassword = ''
  passwordForm.confirmPassword = ''
  changePasswordDialogVisible.value = true
}

// 修改密码
// const changePassword = async () => {
//   try {
//     const valid = await passwordFormRef.value.validate()
//     if (!valid) return
//
//     // 调用后端修改密码接口
//     // 注意：这里需要根据您的实际后端API实现
//     const response = await axios.post('/api/user/change-password', {
//       username: userInfo.userName,
//       currentPassword: passwordForm.currentPassword,
//       newPassword: passwordForm.newPassword
//
//     })
//
//     ElMessage.success('密码修改成功')
//     changePasswordDialogVisible.value = false
//
//   } catch (error) {
//     console.error('密码修改失败:', error)
//     ElMessage.error('密码修改失败: ' + (error.response?.data?.message || error.message))
//   }
// }

// 退出登录
const logout = () => {
  // 清除本地存储的用户信息
  localStorage.removeItem('username')
  // 跳转到登录页面
  router.push('/login')
  ElMessage.success('已退出登录')
}

// 返回上一页
const goBack = () => {
  router.go(-1)
}

// 组件挂载时获取用户信息
onMounted(() => {
  fetchUserProfile()
})
</script>

<style scoped>
.user-info-container {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}

.action-bar {
  margin-bottom: 20px;
}

.action-btn {
  padding: 8px 15px;
  background-color: #3498db;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.action-btn:hover {
  background-color: #2980b9;
}

.user-info-card {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  padding: 20px;
  max-width: 600px;
  margin: 0 auto;
}

.user-info-card h2 {
  margin-bottom: 20px;
  text-align: center;
  color: #333;
}

.action-buttons {
  margin-top: 20px;
  display: flex;
  justify-content: space-between;
}

.el-dialog {
  width: 400px;
}

.loading-container {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}
</style>